<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue';
import { useRouter } from 'vue-router';

import { IconifyIcon } from '@vben/icons';

import {
  Button,
  Card,
  Checkbox,
  Col,
  DatePicker,
  Form,
  FormItem,
  Input,
  message,
  Modal,
  Radio,
  Row,
  Select,
  SelectOption,
  Space,
  Table,
  Tag,
  Textarea,
  Timeline,
  TimelineItem,
  TimePicker,
} from 'ant-design-vue';
import dayjs from 'dayjs';

import StatisticsCard from '#/components/hotel/StatisticsCard.vue';

const router = useRouter();

// 清洁任务状态枚举
enum CleaningTaskStatus {
  ASSIGNED = 'assigned',
  CANCELLED = 'cancelled',
  COMPLETED = 'completed',
  PENDING = 'pending',
  PROCESSING = 'processing',
}

// 响应式数据
const showAddTaskModal = ref(false);
const showAddStaffModal = ref(false);
const showInspectionModal = ref(false);

// 清洁任务表单
const taskForm = reactive({
  roomNumber: '',
  type: '',
  plannedDate: null,
  plannedTime: null,
  requirements: '',
  priority: 'medium',
  remarks: '',
});

// 清洁人员表单
const staffForm = reactive({
  name: '',
  phone: '',
  idCard: '',
  experience: '',
  specialties: [],
  remarks: '',
});

// 质量检查表单
const inspectionForm = reactive({
  roomNumber: '',
  items: {
    floor: false,
    bathroom: false,
    kitchen: false,
    bedroom: false,
    living: false,
    balcony: false,
  },
  passed: true,
  remarks: '',
});

// 检查项目配置
const inspectionItems = [
  { key: 'floor', label: '地面清洁' },
  { key: 'bathroom', label: '卫生间清洁' },
  { key: 'kitchen', label: '厨房清洁' },
  { key: 'bedroom', label: '卧室清洁' },
  { key: 'living', label: '客厅清洁' },
  { key: 'balcony', label: '阳台清洁' },
];

// 可用房间数据
const availableRooms = ref([
  { id: '101', roomNumber: '101' },
  { id: '102', roomNumber: '102' },
  { id: '201', roomNumber: '201' },
  { id: '202', roomNumber: '202' },
  { id: '301', roomNumber: '301' },
]);

// 统计信息
const statistics = computed(() => {
  return {
    todayTasks: 8,
    processingTasks: 3,
    completedTasks: 5,
    totalStaff: 12,
    pendingTasks: 2,
    activeStaff: 10,
    todayAttendance: 8,
    avgRating: 4.2,
    standardCount: 15,
    todayInspections: 6,
    passRate: 85,
  };
});

// 今日任务数据
const todayTasks = ref([
  {
    id: '1',
    roomNumber: '101',
    type: 'regular',
    status: CleaningTaskStatus.PROCESSING,
    priority: 'medium',
    assignedTo: '张阿姨',
    plannedTime: '09:00',
    requirements: '日常清洁，重点卫生间',
  },
  {
    id: '2',
    roomNumber: '201',
    type: 'checkout',
    status: CleaningTaskStatus.ASSIGNED,
    priority: 'high',
    assignedTo: '李阿姨',
    plannedTime: '10:00',
    requirements: '退租深度清洁',
  },
  {
    id: '3',
    roomNumber: '301',
    type: 'deep',
    status: CleaningTaskStatus.COMPLETED,
    priority: 'medium',
    assignedTo: '王阿姨',
    plannedTime: '08:00',
    requirements: '深度清洁，包括家具',
  },
]);

// 最近检查记录
const recentInspections = ref([
  {
    id: '1',
    roomNumber: '101',
    inspectorName: '质检员A',
    passed: true,
    remarks: '清洁质量良好，符合标准',
    inspectionTime: dayjs().subtract(1, 'hour'),
  },
  {
    id: '2',
    roomNumber: '201',
    inspectorName: '质检员B',
    passed: false,
    remarks: '卫生间清洁不彻底，需要返工',
    inspectionTime: dayjs().subtract(2, 'hour'),
  },
  {
    id: '3',
    roomNumber: '301',
    inspectorName: '质检员A',
    passed: true,
    remarks: '整体清洁质量优秀',
    inspectionTime: dayjs().subtract(3, 'hour'),
  },
]);

// 今日任务表格列定义
const todayTaskColumns = [
  {
    title: '房间号',
    dataIndex: 'roomNumber',
    key: 'roomNumber',
    width: 80,
  },
  {
    title: '清洁类型',
    dataIndex: 'type',
    key: 'type',
    width: 100,
    customRender: ({ text }: any) => getTaskTypeText(text),
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
  },
  {
    title: '优先级',
    dataIndex: 'priority',
    key: 'priority',
    width: 100,
  },
  {
    title: '分派给',
    dataIndex: 'assignedTo',
    key: 'assignedTo',
    width: 100,
  },
  {
    title: '计划时间',
    dataIndex: 'plannedTime',
    key: 'plannedTime',
    width: 100,
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
  },
];

// 工具函数
const getTaskStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    [CleaningTaskStatus.PENDING]: 'orange',
    [CleaningTaskStatus.ASSIGNED]: 'blue',
    [CleaningTaskStatus.PROCESSING]: 'processing',
    [CleaningTaskStatus.COMPLETED]: 'success',
    [CleaningTaskStatus.CANCELLED]: 'default',
  };
  return colorMap[status] || 'default';
};

const getTaskStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    [CleaningTaskStatus.PENDING]: '待处理',
    [CleaningTaskStatus.ASSIGNED]: '已分派',
    [CleaningTaskStatus.PROCESSING]: '进行中',
    [CleaningTaskStatus.COMPLETED]: '已完成',
    [CleaningTaskStatus.CANCELLED]: '已取消',
  };
  return statusMap[status] || status;
};

const getTaskTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    regular: '定期清洁',
    checkout: '退租清洁',
    deep: '深度清洁',
    emergency: '紧急清洁',
  };
  return typeMap[type] || type;
};

const getPriorityColor = (priority: string) => {
  const colorMap: Record<string, string> = {
    low: 'default',
    medium: 'orange',
    high: 'red',
  };
  return colorMap[priority] || 'default';
};

const getPriorityText = (priority: string) => {
  const priorityMap: Record<string, string> = {
    low: '一般',
    medium: '重要',
    high: '紧急',
  };
  return priorityMap[priority] || priority;
};

const formatDateTime = (datetime: any) => {
  return datetime ? dayjs(datetime).format('YYYY-MM-DD HH:mm') : '';
  datetimedayjs.format;
};

// 导航函数
const navigateToTasks = () => {
  router.push('/hotel/cleaning/tasks');
};

const navigateToStaff = () => {
  router.push('/hotel/cleaning/staff');
};

const navigateToStandards = () => {
  router.push('/hotel/cleaning/standards');
};

const navigateToInspection = () => {
  router.push('/hotel/cleaning/inspection');
};

const navigateToRecords = () => {
  router.push('/hotel/cleaning/records');
};

// 事件处理函数
const handleAssignTask = (record: any) => {
  message.success(`已分派任务给 ${record.assignedTo}`);
  // 这里可以更新任务状态
};

const handleStartTask = (record: any) => {
  message.success(`开始执行清洁任务`);
  // 这里可以更新任务状态
};

const handleCompleteTask = (record: any) => {
  message.success(`清洁任务已完成`);
  // 这里可以更新任务状态
};

const handleInspectTask = (record: any) => {
  inspectionForm.roomNumber = record.roomNumber;
  showInspectionModal.value = true;
};

const handleAddTask = () => {
  if (!taskForm.roomNumber || !taskForm.type || !taskForm.plannedDate) {
    message.error('请填写完整的任务信息');
    return;
  }

  message.success('清洁任务创建成功');
  showAddTaskModal.value = false;
  handleCancelTask();
};

const handleCancelTask = () => {
  Object.assign(taskForm, {
    roomNumber: '',
    type: '',
    plannedDate: null,
    plannedTime: null,
    requirements: '',
    priority: 'medium',
    remarks: '',
  });
};

const handleAddStaff = () => {
  if (!staffForm.name || !staffForm.phone) {
    message.error('请填写完整的人员信息');
    return;
  }

  message.success('清洁人员添加成功');
  showAddStaffModal.value = false;
  handleCancelStaff();
};

const handleCancelStaff = () => {
  Object.assign(staffForm, {
    name: '',
    phone: '',
    idCard: '',
    experience: '',
    specialties: [],
    remarks: '',
  });
};

const handleInspectionSubmit = () => {
  if (!inspectionForm.roomNumber) {
    message.error('请选择检查房间');
    return;
  }

  message.success('质量检查提交成功');
  showInspectionModal.value = false;
  handleCancelInspection();
};

const handleCancelInspection = () => {
  Object.assign(inspectionForm, {
    roomNumber: '',
    items: {
      floor: false,
      bathroom: false,
      kitchen: false,
      bedroom: false,
      living: false,
      balcony: false,
    },
    passed: true,
    remarks: '',
  });
};

// 初始化
onMounted(() => {
  console.log('清洁管理页面已加载');
});
</script>

<template>
  <div class="cleaning-management">
    <div class="page-header">
      <h2>清洁管理</h2>
      <Button type="primary" @click="showAddTaskModal = true">
        <IconifyIcon icon="ant-design:plus-outlined" />
        新建清洁任务
      </Button>
    </div>

    <!-- 统计卡片 -->
    <Row :gutter="16" class="statistics-row">
      <Col :span="6">
        <StatisticsCard
          title="今日任务"
          :value="statistics.todayTasks"
          color="#1890ff"
          icon="ant-design:calendar-outlined"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="进行中"
          :value="statistics.processingTasks"
          color="#faad14"
          icon="ant-design:clock-circle-outlined"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="已完成"
          :value="statistics.completedTasks"
          color="#52c41a"
          icon="ant-design:check-circle-outlined"
        />
      </Col>
      <Col :span="6">
        <StatisticsCard
          title="清洁人员"
          :value="statistics.totalStaff"
          color="#722ed1"
          icon="ant-design:team-outlined"
        />
      </Col>
    </Row>

    <!-- 功能模块 -->
    <Row :gutter="16" class="module-row">
      <Col :span="8">
        <Card title="清洁任务" :bordered="false" class="module-card">
          <div class="module-content">
            <div class="module-stats">
              <div class="stat-item">
                <span class="stat-label">待处理：</span>
                <span class="stat-value pending">{{
                  statistics.pendingTasks
                }}</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">进行中：</span>
                <span class="stat-value processing">{{
                  statistics.processingTasks
                }}</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">已完成：</span>
                <span class="stat-value completed">{{
                  statistics.completedTasks
                }}</span>
              </div>
            </div>
            <div class="module-actions">
              <Button type="primary" @click="showAddTaskModal = true">
                <IconifyIcon icon="ant-design:plus-outlined" />
                新建任务
              </Button>
              <Button @click="navigateToTasks">
                <IconifyIcon icon="ant-design:eye-outlined" />
                查看全部
              </Button>
              <Button @click="navigateToRecords">
                <IconifyIcon icon="ant-design:history-outlined" />
                记录追踪
              </Button>
            </div>
          </div>
        </Card>
      </Col>

      <Col :span="8">
        <Card title="人员管理" :bordered="false" class="module-card">
          <div class="module-content">
            <div class="module-stats">
              <div class="stat-item">
                <span class="stat-label">在职人员：</span>
                <span class="stat-value active">{{
                  statistics.activeStaff
                }}</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">今日出勤：</span>
                <span class="stat-value today">{{
                  statistics.todayAttendance
                }}</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">平均评分：</span>
                <span class="stat-value rating"
                  >{{ statistics.avgRating }}分</span
                >
              </div>
            </div>
            <div class="module-actions">
              <Button type="primary" @click="showAddStaffModal = true">
                <IconifyIcon icon="ant-design:user-add-outlined" />
                添加人员
              </Button>
              <Button @click="navigateToStaff">
                <IconifyIcon icon="ant-design:team-outlined" />
                人员管理
              </Button>
            </div>
          </div>
        </Card>
      </Col>

      <Col :span="8">
        <Card title="质量标准" :bordered="false" class="module-card">
          <div class="module-content">
            <div class="module-stats">
              <div class="stat-item">
                <span class="stat-label">标准数量：</span>
                <span class="stat-value total">{{
                  statistics.standardCount
                }}</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">今日检查：</span>
                <span class="stat-value today">{{
                  statistics.todayInspections
                }}</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">合格率：</span>
                <span class="stat-value passRate"
                  >{{ statistics.passRate }}%</span
                >
              </div>
            </div>
            <div class="module-actions">
              <Button type="primary" @click="showAddStandardModal = true">
                <IconifyIcon icon="ant-design:setting-outlined" />
                设置标准
              </Button>
              <Button @click="navigateToStandards">
                <IconifyIcon icon="ant-design:audit-outlined" />
                标准管理
              </Button>
              <Button @click="navigateToInspection">
                <IconifyIcon icon="ant-design:audit-outlined" />
                质量检查
              </Button>
            </div>
          </div>
        </Card>
      </Col>
    </Row>

    <!-- 今日任务列表 -->
    <Card title="今日清洁任务" :bordered="false" class="task-card">
      <Table
        :columns="todayTaskColumns"
        :data-source="todayTasks"
        :pagination="false"
        size="small"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <Tag :color="getTaskStatusColor(record.status)">
              {{ getTaskStatusText(record.status) }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'priority'">
            <Tag :color="getPriorityColor(record.priority)">
              {{ getPriorityText(record.priority) }}
            </Tag>
          </template>
          <template v-else-if="column.key === 'action'">
            <Space>
              <Button
                v-if="record.status === 'pending'"
                type="link"
                size="small"
                @click="handleAssignTask(record)"
              >
                分派
              </Button>
              <Button
                v-if="record.status === 'assigned'"
                type="link"
                size="small"
                @click="handleStartTask(record)"
              >
                开始
              </Button>
              <Button
                v-if="record.status === 'processing'"
                type="link"
                size="small"
                @click="handleCompleteTask(record)"
              >
                完成
              </Button>
              <Button
                type="link"
                size="small"
                @click="handleInspectTask(record)"
              >
                检查
              </Button>
            </Space>
          </template>
        </template>
      </Table>
    </Card>

    <!-- 质量检查记录 -->
    <Card title="最近质量检查" :bordered="false" class="inspection-card">
      <Timeline>
        <TimelineItem
          v-for="inspection in recentInspections"
          :key="inspection.id"
        >
          <template #dot>
            <IconifyIcon
              :icon="
                inspection.passed
                  ? 'ant-design:check-circle-outlined'
                  : 'ant-design:close-circle-outlined'
              "
              :style="{ color: inspection.passed ? '#52c41a' : '#ff4d4f' }"
            />
          </template>
          <div class="inspection-content">
            <div class="inspection-title">
              {{ inspection.roomNumber }} - {{ inspection.inspectorName }}
            </div>
            <div class="inspection-desc">
              {{ inspection.passed ? '检查通过' : '检查不通过' }} -
              {{ inspection.remarks }}
            </div>
            <div class="inspection-time">
              {{ formatDateTime(inspection.inspectionTime) }}
            </div>
          </div>
        </TimelineItem>
      </Timeline>
    </Card>

    <!-- 新建清洁任务弹窗 -->
    <Modal
      v-model:open="showAddTaskModal"
      title="新建清洁任务"
      width="600px"
      @ok="handleAddTask"
      @cancel="handleCancelTask"
    >
      <Form :model="taskForm" layout="vertical">
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="清洁房间" name="roomNumber">
              <Select
                v-model:value="taskForm.roomNumber"
                placeholder="请选择房间"
                style="width: 100%"
              >
                <SelectOption
                  v-for="room in availableRooms"
                  :key="room.id"
                  :value="room.roomNumber"
                >
                  {{ room.roomNumber }}
                </SelectOption>
              </Select>
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="清洁类型" name="type">
              <Select
                v-model:value="taskForm.type"
                placeholder="请选择清洁类型"
                style="width: 100%"
              >
                <SelectOption value="regular">定期清洁</SelectOption>
                <SelectOption value="checkout">退租清洁</SelectOption>
                <SelectOption value="deep">深度清洁</SelectOption>
                <SelectOption value="emergency">紧急清洁</SelectOption>
              </Select>
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="16">
          <Col :span="12">
            <FormItem label="计划日期" name="plannedDate">
              <DatePicker
                v-model:value="taskForm.plannedDate"
                style="width: 100%"
                placeholder="请选择计划日期"
              />
            </FormItem>
          </Col>
          <Col :span="12">
            <FormItem label="计划时间" name="plannedTime">
              <TimePicker
                v-model:value="taskForm.plannedTime"
                style="width: 100%"
                placeholder="请选择计划时间"
              />
            </FormItem>
          </Col>
        </Row>
        <FormItem label="清洁要求" name="requirements">
          <Textarea
            v-model:value="taskForm.requirements"
            placeholder="请描述清洁要求"
            :rows="3"
          />
        </FormItem>
        <FormItem label="优先级" name="priority">
          <Select
            v-model:value="taskForm.priority"
            placeholder="请选择优先级"
            style="width: 100%"
          >
            <SelectOption value="low">一般</SelectOption>
            <SelectOption value="medium">重要</SelectOption>
            <SelectOption value="high">紧急</SelectOption>
          </Select>
        </FormItem>
        <FormItem label="备注" name="remarks">
          <Textarea
            v-model:value="taskForm.remarks"
            placeholder="请输入备注信息"
            :rows="2"
          />
        </FormItem>
      </Form>
    </Modal>

    <!-- 添加清洁人员弹窗 -->
    <Modal
      v-model:open="showAddStaffModal"
      title="添加清洁人员"
      width="500px"
      @ok="handleAddStaff"
      @cancel="handleCancelStaff"
    >
      <Form :model="staffForm" layout="vertical">
        <FormItem label="姓名" name="name">
          <Input v-model:value="staffForm.name" placeholder="请输入姓名" />
        </FormItem>
        <FormItem label="联系电话" name="phone">
          <Input v-model:value="staffForm.phone" placeholder="请输入联系电话" />
        </FormItem>
        <FormItem label="身份证号" name="idCard">
          <Input
            v-model:value="staffForm.idCard"
            placeholder="请输入身份证号"
          />
        </FormItem>
        <FormItem label="工作经验" name="experience">
          <Select
            v-model:value="staffForm.experience"
            placeholder="请选择工作经验"
            style="width: 100%"
          >
            <SelectOption value="0-1">0-1年</SelectOption>
            <SelectOption value="1-3">1-3年</SelectOption>
            <SelectOption value="3-5">3-5年</SelectOption>
            <SelectOption value="5+">5年以上</SelectOption>
          </Select>
        </FormItem>
        <FormItem label="专长领域" name="specialties">
          <Select
            v-model:value="staffForm.specialties"
            mode="multiple"
            placeholder="请选择专长领域"
            style="width: 100%"
          >
            <SelectOption value="regular">日常清洁</SelectOption>
            <SelectOption value="deep">深度清洁</SelectOption>
            <SelectOption value="checkout">退租清洁</SelectOption>
            <SelectOption value="emergency">紧急清洁</SelectOption>
          </Select>
        </FormItem>
        <FormItem label="备注" name="remarks">
          <Textarea
            v-model:value="staffForm.remarks"
            placeholder="请输入备注信息"
            :rows="2"
          />
        </FormItem>
      </Form>
    </Modal>

    <!-- 质量检查弹窗 -->
    <Modal
      v-model:open="showInspectionModal"
      title="质量检查"
      width="600px"
      @ok="handleInspectionSubmit"
      @cancel="handleCancelInspection"
    >
      <Form :model="inspectionForm" layout="vertical">
        <FormItem label="检查房间" name="roomNumber">
          <Input v-model:value="inspectionForm.roomNumber" disabled />
        </FormItem>
        <FormItem label="检查项目" name="items">
          <div class="inspection-items">
            <div
              v-for="item in inspectionItems"
              :key="item.key"
              class="inspection-item"
            >
              <Checkbox v-model:checked="inspectionForm.items[item.key]">
                {{ item.label }}
              </Checkbox>
            </div>
          </div>
        </FormItem>
        <FormItem label="检查结果" name="passed">
          <Radio.Group v-model:value="inspectionForm.passed">
            <Radio :value="true">通过</Radio>
            <Radio :value="false">不通过</Radio>
          </Radio.Group>
        </FormItem>
        <FormItem label="检查备注" name="remarks">
          <Textarea
            v-model:value="inspectionForm.remarks"
            placeholder="请输入检查备注"
            :rows="3"
          />
        </FormItem>
      </Form>
    </Modal>
  </div>
</template>

<style scoped>
.cleaning-management {
  padding: 16px;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
}

.statistics-row {
  margin-bottom: 24px;
}

.module-row {
  margin-bottom: 24px;
}

.module-card {
  height: 200px;
}

.module-content {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 100%;
}

.module-stats {
  margin-bottom: 16px;
}

.stat-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 14px;
}

.stat-label {
  color: #666;
}

.stat-value {
  font-weight: 600;
}

.stat-value.pending {
  color: #ff4d4f;
}

.stat-value.processing {
  color: #1890ff;
}

.stat-value.completed {
  color: #52c41a;
}

.stat-value.active {
  color: #52c41a;
}

.stat-value.today {
  color: #faad14;
}

.stat-value.rating {
  color: #722ed1;
}

.stat-value.total {
  color: #666;
}

.stat-value.passRate {
  color: #52c41a;
}

.module-actions {
  display: flex;
  gap: 8px;
}

.task-card {
  margin-bottom: 24px;
}

.inspection-card {
  margin-bottom: 24px;
}

.inspection-content {
  padding-left: 8px;
}

.inspection-title {
  margin-bottom: 4px;
  font-weight: 500;
  color: #1f2937;
}

.inspection-desc {
  margin-bottom: 4px;
  font-size: 14px;
  color: #666;
}

.inspection-time {
  font-size: 12px;
  color: #999;
}

.inspection-items {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.inspection-item {
  display: flex;
  align-items: center;
}

:deep(.ant-timeline-item-head) {
  background-color: transparent;
}

:deep(.ant-timeline-item-tail) {
  border-left: 1px solid #f0f0f0;
}

:deep(.ant-table-thead > tr > th) {
  font-weight: 600;
  background-color: #fafafa;
}
</style>
